var express = require('express');
var router = express.Router();

var path = require('path');
var CONFIG = require('../../common/config');
var CODE = require('../../common/code');
var FileDownLoader = require('../../common/util/FileDownLoader');
var FileUpLoader = require('../../common/util/FileUpLoader');
var FileUtil = require('../../common/util/FileUtil');
var CommonUtil = require('../../common/util/CommonUtil');

//------------------------------------------------------------------
// 取得image服务的图片生成路径的根目录：如  '/root/image/public/create/'
function getImageOutputDir(){
    var ret =  __dirname+'/../'+CONFIG.CREATE_IAMGE_DIR;
    ret = path.resolve(ret)+'/';
    return ret;
}
function uploadFile(localFile, nonthing, nonthing, callback) {
    var dir = getImageOutputDir();
    var object_key = localFile.substring(dir.length);
    FileUpLoader.upload(localFile,object_key, CONFIG.BUCKET_ITBOUR_USER,function(err, url){
        callback(err,url);
    });
}
/* 重新保存图片.
 * 方式:GET
 * 参数:device:
 * 参数:url:图片地址
 * 参数:user_id:用户id
 * 返回:新的url
 * */
function resaveImage(req, res, next) {
    var url = req.query.url || req.body.url;
    var user_id =Number( req.query.user_id || req.body.user_id ||0);

    // return function
    function ret_func(success, msg, data){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    }

    if(!user_id){
        return ret_func(0, CODE.USER_ID_EMPTY);
    }


    var dir = getImageOutputDir()+CommonUtil.getUploadFileName(0, user_id);
    FileUtil.mkdirs(dir,function(err) {
        if (err) {
            console.log('FileUtil.mkdirs:' + dir + ' ' + err);
        }
        console.time('---->imageCore.js prePiddleProcee,createimage,upload,updateDB');

        FileDownLoader.downloadByURL(url, dir+'/'+CommonUtil.randomString(5), function(err2, path){
            if(err2){
                console.log('FileDownLoader.downloadByURL:' + url + ' ' + err2);
                return ret_func(0, CODE.OPERATION_FAILED);
            }

            uploadFile(path, null,null, function(err3,newUrl){
                // 删除临时文件夹
                FileUtil.rmdir(dir, function(){});

                if(err3){
                    console.log('uploadFile:' + path + ' ' + err3);
                    return ret_func(0, CODE.OPERATION_FAILED);
                }

                return ret_func(1, CODE.OPERATION_SUCCESS, newUrl);
            });
        }, true);
    });
}

router.get('/resaveImage', resaveImage);
router.post('/resaveImage', resaveImage);




module.exports = router;
